package managedbean.stakeholder;

import entity.AdvertisingEntity;
import entity.MetaCategoryEntity;
import entity.MetaCuisineEntity;
import entity.MetaFoodPlaceEntity;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import session.stateless.StakeholderSessionBeanStateless;
import exception.ExistException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.primefaces.event.FileUploadEvent;
import session.stateless.SystemMessagesBean;
import session.stateless.AdvertisementSessionBean;
import util.entityhelper.StakeholderAccountState;
import util.enumeration.ActivityType;
import util.enumeration.CuisineType;
import util.enumeration.FnbType;
import util.localization.WebLocalization;

/**
 *
 * @author KohLi
 */
@ManagedBean
@ViewScoped
public class AddAdvertisementManagedBean implements Serializable {

    private AdvertisingEntity advertisement;
    private Long stakeholderId;
    private String nextPage;
    private FacesContext ctx = FacesContext.getCurrentInstance();
    @EJB
    private AdvertisementSessionBean advertisementSessionBean;
    @EJB
    private SystemMessagesBean systemMessages;
    private String preferredLocale;
    private WebLocalization localization;
    private Long adId;
    private List<CuisineType> cuisineTypeList;
    private List<ActivityType> activityTypeList;
    private List<FnbType> fnbTypeList;

    /*constructor*/
    public AddAdvertisementManagedBean() {
        advertisement = new AdvertisingEntity();
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */
        this.cuisineTypeList = new ArrayList<CuisineType>();
        this.fnbTypeList = new ArrayList<FnbType>();
        this.activityTypeList = new ArrayList<ActivityType>();

        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("selectedAd")) {
            advertisement = (AdvertisingEntity) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedAd");
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedAd", null);
            adId = advertisement.getId();
            loadMetaData(advertisement);

        }

    }

    private void loadMetaData(AdvertisingEntity advertisement) {
        MetaCategoryEntity cat = new MetaCategoryEntity();
        MetaCuisineEntity cuisine = new MetaCuisineEntity();
        MetaFoodPlaceEntity suitable = new MetaFoodPlaceEntity();
        if (!advertisement.getActivityType().isEmpty()) {
            for (int i = 0; i < advertisement.getActivityType().size(); i++) {
                cat = advertisement.getActivityType().get(i);
                activityTypeList.add(cat.getActivityCategory());
            }
        }
        if(!advertisement.getCuisineTypeList().isEmpty()){
            for(int i =0; i<advertisement.getCuisineTypeList().size(); i++){
                cuisine = advertisement.getCuisineTypeList().get(i);
                cuisineTypeList.add(cuisine.getCusine());
            }
        }
        if(!advertisement.getFnBTypeList().isEmpty()){
            for(int i =0; i<advertisement.getFnBTypeList().size(); i++){
                suitable = advertisement.getFnBTypeList().get(i);
                fnbTypeList.add(suitable.getSuitableFor());
            }
        }


    }

    public void initView(PhaseEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        FacesContext.getCurrentInstance().getExternalContext().getFlash().clear();
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

        stakeholderId = (Long) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("stakeholderId");


        if (stakeholderId == null) {

            nextPage = (FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/StakeholderLogin.xhtml")));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(nextPage);
            } catch (IOException ioe) {
                ioe.printStackTrace();

            }
        } else {
        }


    }

    public void handleImageUpload(FileUploadEvent event) throws AbortProcessingException, NoSuchAlgorithmException {

        try {
            String filePath =
                    FacesContext.getCurrentInstance().getExternalContext().getRealPath("images/ads");
            System.out.println("filePath is: " + filePath);
            File result = new File(filePath + System.getProperty("file.separator") + event.getFile().getFileName());
            FileOutputStream out = new FileOutputStream(result);

            int a;
            int BUFFER_SIZE = 8192;
            byte[] buffer = new byte[BUFFER_SIZE];

            InputStream is = event.getFile().getInputstream();

            while (true) {
                a = is.read(buffer);

                if (a < 0) {
                    break;
                }

                out.write(buffer, 0, a);
                out.flush();
            }

            out.close();
            is.close();

            String imgUrl = "/images/ads/" + event.getFile().getFileName();
            advertisement.setPromotionImageUrl(imgUrl);
            System.out.println("imagefilepath: " + imgUrl);
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
            FacesContext.getCurrentInstance().addMessage(null, msg);

        } catch (IOException e) {
            FacesContext.getCurrentInstance().addMessage("", new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "File upload failed with I/O error.", null));
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void saveAdvertisement(ActionEvent event) {

        System.out.println("saving advertisement in process...");
        boolean success = false;
        String statusMessage = " ";
        try {
            if (checkDate(advertisement)) {
                if (adId == null) {
                    //check the date
                    System.out.println("enter here");

                    try {

                        success = advertisementSessionBean.addAdvertisement(advertisement, stakeholderId, activityTypeList, cuisineTypeList, fnbTypeList);

                        if (success) {
                            //String statusMessage = getSystemMessages().getSystemMessage("PROMOTION_CREATION_SUCCESS", getPreferredLocale());
                            statusMessage = "Successfully add the promotion";

                        }

                    } catch (ExistException ex) {
                        FacesMessage msg = new FacesMessage(ex.getMessage());
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                    } catch (Exception ex) {
                        FacesMessage msg = new FacesMessage(ex.getMessage());
                        FacesContext.getCurrentInstance().addMessage(null, msg);
                    }
                } else if (adId != null) {
                    success = advertisementSessionBean.saveEditAds(advertisement, adId, activityTypeList, cuisineTypeList, fnbTypeList);
                    if (success) {
                        //String statusMessage = getSystemMessages().getSystemMessage("PROMOTION_CREATION_SUCCESS", getPreferredLocale());
                        statusMessage = "Successfully edited the promotion.";

                    }

                }
                if (success == true) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, ""));
                } else {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, ""));
                }
            }//if check date = success;
        } catch (ExistException ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
        }

    }

    public void saveEditAdvertisement(ActionEvent event) {
    }

    private boolean checkDate(AdvertisingEntity ad) throws ExistException {
        boolean success = true;
        Date today = new Date();

        Date todayDate = new Date();

        if (advertisement.getEndDate().before(today) && advertisement.getStartDate().before(today)) {
            success = false;
            throw new ExistException("Advertising dates cannot be before Today.");
        } else if (advertisement.getStartDate().after(advertisement.getEndDate())) {
            success = false;
            throw new ExistException("Advertising end date cannot be before start date.");
        }
        return success;

    }

    /**
     * @return the advertisement
     */
    public AdvertisingEntity getAdvertisement() {
        return advertisement;
    }

    /**
     * @param advertisement the advertisement to set
     */
    public void setAdvertisement(AdvertisingEntity advertisement) {
        this.advertisement = advertisement;
    }

    /**
     * @return the stakeholderId
     */
    public Long getStakeholderId() {
        return stakeholderId;
    }

    /**
     * @param stakeholderId the stakeholderId to set
     */
    public void setStakeholderId(Long stakeholderId) {
        this.stakeholderId = stakeholderId;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @return the preferredLocale
     */
    public String getPreferredLocale() {
        return preferredLocale;
    }

    /**
     * @param preferredLocale the preferredLocale to set
     */
    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    /**
     * @return the localization
     */
    public WebLocalization getLocalization() {
        return localization;
    }

    /**
     * @param localization the localization to set
     */
    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    /**
     * @return the adId
     */
    public Long getAdId() {
        return adId;
    }

    /**
     * @param adId the adId to set
     */
    public void setAdId(Long adId) {
        this.adId = adId;
    }

    /**
     * @return the cuisineTypeList
     */
    public List<CuisineType> getCuisineTypeList() {
        return cuisineTypeList;
    }

    /**
     * @param cuisineTypeList the cuisineTypeList to set
     */
    public void setCuisineTypeList(List<CuisineType> cuisineTypeList) {
        this.cuisineTypeList = cuisineTypeList;
    }

    /**
     * @return the activityTypeList
     */
    public List<ActivityType> getActivityTypeList() {
        return activityTypeList;
    }

    /**
     * @param activityTypeList the activityTypeList to set
     */
    public void setActivityTypeList(List<ActivityType> activityTypeList) {
        this.activityTypeList = activityTypeList;
    }

    /**
     * @return the fnbTypeList
     */
    public List<FnbType> getFnbTypeList() {
        return fnbTypeList;
    }

    /**
     * @param fnbTypeList the fnbTypeList to set
     */
    public void setFnbTypeList(List<FnbType> fnbTypeList) {
        this.fnbTypeList = fnbTypeList;
    }
}

